package enhance.plus.util;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import common.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubo
 * @created 2020-07-17 17:32
 */
@Slf4j
public class MybatisPlusUtil {

    public static Map<String,Object> convertParamToMap(Object param, Class help){
        Map<String , Object> result = new HashMap<>();
        Map<String,Object> paramMap =  CommonUtil.convertBeanToMap(param);
        List<Field> fields = CommonUtil.getFieldList(help);
        Map<String,String> fieldMap = new HashMap<>();
        for (Field field : fields) {
            TableField tf = field.getAnnotation(TableField.class);
            TableId ti = field.getAnnotation(TableId.class);
            String key = null;
            if(CommonUtil.isNotEmpty(tf)){
                key = tf.value();
            } else if(CommonUtil.isNotEmpty(ti)){
                key = ti.value();
            }
            if(CommonUtil.isEmpty(key)) {
                key = CommonUtil.dbHumpToDB(field.getName());
            }
            fieldMap.put(field.getName(), key);
        }
        int flag =0;
        for (String key : fieldMap.keySet()) {
            if(key.equals("size")|| key.equals("current")){
                ++flag;
            }
           Object value = paramMap.get(key);
           if(CommonUtil.isNotEmpty(value)){
               result.put(fieldMap.get(key),value);
           }
        }
        if(flag ==2){
            result.remove("size");
            result.remove("current");
        }
        if(CommonUtil.isEmpty(result)){
            log.debug("参数为空,请注意");
        }
        return result;
    }
}
